<template>
  <view style="position: relative">
    <view class="serach">
      <u-search shape="square" action-text="" :action-style="{'display':'none'}" v-model="keyword"
                bgColor="#ffffff" padding="30rpx" placeholder="输入城市名" height="64" @search="onSearch" @change="onSearch"
                @clear="clearSearch">
      </u-search>
    </view>
    <view class="serach-content" ref='serach' v-if="keyword">
      <view class="serach-item border-bottom"
          v-for="(item,index) in list"
          :key='item.id'
          @click="handleclick(item)">
        {{item.name}}
      </view>
      <view class="serach-item border-bottom" style="text-align: center" v-if="list.length==0">未找到匹配项</view>
    </view>
  </view>
</template>

<script>
import Bscroll from 'better-scroll'
import { mapActions } from 'vuex'
export default {
  name: 'CitySerach',
  props: {
    cities: Array
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  methods: {
    clearSearch(){
      this.keyword=''
    },
    onSearch(){
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return this.list
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i = 0; i< this.cities.length; i++) {
          this.cities[i].list.forEach((value) => {
            if (value.pinyin.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
            this.list = result
          })
        }
      }, 100)
    },
    handleclick (city) {
      this.changecity(city)
      setTimeout(()=>{
        uni.switchTab({
          url: '/pages/index/index'
        })
      },500)
    },
    ...mapActions(['changecity'])
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.serach, {
      click: true
    })
  },
  computed: {
    hasNodata () {
      return !this.list.length
    }
  },
  watch: {
  }
}
</script>

<style lang="scss" scoped>
.serach{
  height: 72rpx;
  padding:10rpx;
  .serach-input{
    width: 100%;
    height: 62rpx;
    line-height: 62rpx;
    text-align: center;
    border-radius: 40rpx;
    padding: 0 10rpx;
    box-sizing: border-box;
    color: #333;
  }
}
.serach-content {
  z-index: 300;
  overflow: scroll;
  position: absolute;
  top: 78rpx;
  right: 0;
  left: 0;
  bottom: 0;
  background: #fff;
  border-radius: 20rpx 20rpx 20rpx 20rpx;
  height: 200rpx;
}
.serach-item {
  height: 62rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  color: #666;
  background-color: #fff;
}
</style>
